package com.example.tech.folio.config;

import com.example.tech.folio.interceptor.SessionInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * Spring MVC配置
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    // 添加日期转换器，用于处理请求参数中的日期格式
    @Override
    public void addFormatters(FormatterRegistry registry) {
        DateTimeFormatter isoDateFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
        registry.addConverter(String.class, LocalDate.class, source -> {
            if (source == null || source.isEmpty()) {
                return null;
            }
            if (source.matches("\\d{4}-\\d{2}")) {
                source += "-01";
            }
            return LocalDate.parse(source, isoDateFormatter);
        });
    }

    // 添加Session拦截器，用于检查用户是否登录
    @Autowired
    private SessionInterceptor sessionInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePathPatterns = new ArrayList<>();
        excludePathPatterns.add("/");
        excludePathPatterns.add("/css/**");
        excludePathPatterns.add("/image/**");
        excludePathPatterns.add("/js/**");
        excludePathPatterns.add("/index.html");
        excludePathPatterns.add("/admin/login.html");
        excludePathPatterns.add("/api/admin/login");
        excludePathPatterns.add("/api/profile/public/**");
        excludePathPatterns.add("/api/project/public/**");

        registry.addInterceptor(sessionInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(excludePathPatterns);
    }
}
